﻿using AbpApplication.Expand;
using AbpApplication.Flurl;
using AbpApplication.InPut;
using AbpToDomain.EntityInfo;
using Castle.Core.Logging;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using NLog;
using SingalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;
using wms_wpf.Apiservice;

namespace AbpApplication.AppServices
{

    public class EssService : ApplicationService, IEssService
    {
        private readonly IRepository<TaskOrder> TaskOrder_res;
        private readonly IRepository<Box> box_res;
        private readonly IRepository<WarehouseLine> warehouse_line_res;
        private readonly IRepository<InlethouseLine> inlethouseline_res;
        private readonly ILoginHelper loginHelper;
        private readonly IBaseService baseService;
        private readonly IToOutSideInterFace toOutSideInterFace;
        private readonly IRepository<PutInOrder> putinorder_res;



        public EssService(IRepository<TaskOrder> taskOrder_res, IRepository<Box> box_res, IRepository<WarehouseLine> warehouse_line_res, ILoginHelper loginHelper, IBaseService baseService, IRepository<InlethouseLine> inlethouseline_res, IRepository<lognote> logNote_res, IToOutSideInterFace toOutSideInterFace, IRepository<PutInOrder> putinorder_res)
        {
            TaskOrder_res = taskOrder_res;
            this.box_res = box_res;
            this.warehouse_line_res = warehouse_line_res;
            this.loginHelper = loginHelper;
            this.baseService = baseService;
            this.inlethouseline_res = inlethouseline_res;
            this.toOutSideInterFace = toOutSideInterFace;
            this.putinorder_res = putinorder_res;
        }
        public async Task<ApiResponse> AbnormalCapture(InPut_EssService2 InPut)
        {
            return new ApiResponse("ok", true, null);
        }//异常回调


        public async Task<ApiResponseEss> TaskStatusChange(InPut_EssService InPut)
        {
            try
            {
                InPut_BaseService15 record = new InPut_BaseService15();
                record.User = "ESS";
                record.Note = "任务编号：" + InPut.taskCode + "msg：" + InPut.message + "事件类型：" + InPut.eventType + InPut.containerCode + InPut.isLocationHasContainer + InPut.stationCode + "状态：" + InPut.status;
                record.Type = "ESS记录";
                loginHelper.LoginAsync(InPut, $"TaskStatusChange任务回调-日志-{record.Note}");

                if (InPut.eventType == "task")
                {
                    if (InPut.status == "success")
                    {
                        TaskOrder taskOrder = await TaskOrder_res.FirstOrDefaultAsync(x => x.TaskOrderCode == InPut.taskCode);
                        if (taskOrder == null)
                        {
                            loginHelper.LoginAsync(InPut, $"TaskStatusChange-未查询到改任务+{taskOrder.Id_Box + taskOrder.WarehouseCode + taskOrder.TaskOrderCode}");
                            return new ApiResponseEss(0, "success", "fail-未查询到改任务");
                           
                        }
                        if (taskOrder.Type == "出库")
                        {
                            loginHelper.LoginInfoAsync($"task+success+出库{InPut.taskCode}");
                            Box box = await box_res.FirstOrDefaultAsync(x => x.Id_Box == taskOrder.Id_Box);
                            WarehouseLine warehouseLine = await warehouse_line_res.FirstOrDefaultAsync(x => x.WarehouseLineCode == taskOrder.WarehouseCode);
                            InlethouseLine inlethouseLine=  await inlethouseline_res.FirstOrDefaultAsync(x=>x.InlethouseLineCode==taskOrder.InlethouseCode);
                            warehouseLine.IsOccupy = false;
                      
                            if (inlethouseLine != null)
                            {
                                inlethouseLine.Box = box;
                                inlethouseLine.Box = null;
                                inlethouseLine.IsOccupy = false;
                                await inlethouseline_res.UpdateAsync(inlethouseLine);
                            }

                            box.WarehouseLine = null;
                            box.Id_WarehouseLine = null;
                            box.Id_InlethouseLine = null;
                            box.InlethouseLine = null;
                        
                            await box_res.UpdateAsync(box);
                            await warehouse_line_res.UpdateAsync(warehouseLine);
                       
                            await TaskOrder_res.DeleteAsync(taskOrder);
                            if (string.IsNullOrEmpty(taskOrder.OrderNo))
                            {
                                return new ApiResponseEss(0, "success", "success2");
                            }
                            //mes
                            CustomOut_InPut custom_InPut = new CustomOut_InPut();
                            custom_InPut.boxCode = box.BoxCode;
                            custom_InPut.symbol = taskOrder.OrderNo;
                            OutOrderDto outOrderDto = new OutOrderDto
                            {
                                materialCode = "",
                                quantity = 0,
                                result = 0
                            };
                            custom_InPut.outOrderDtos.Add(outOrderDto);
                            await toOutSideInterFace.receiveOutWarehouseResult(custom_InPut);


                            //signalr
                            await UnitOfWorkManager.Current.SaveChangesAsync();
                            Tuple<string,HubConnection> tuple=  await SingalrMethod.GetConnectionAsync();
                            loginHelper.LoginAsync(InPut, $"SignalrInfo+{tuple.Item1}");
                            await tuple.Item2.StopAsync();
                            return new ApiResponseEss(0, "success", "success2");

                        }
                        if (taskOrder.Type == "入库")
                        {
                            loginHelper.LoginInfoAsync($"task+success+入库{InPut.taskCode}");
                            var boxsquery =await box_res.WithDetailsAsync();
                            Box box=await boxsquery.FirstOrDefaultAsync(x => x.Id_Box == taskOrder.Id_Box);
                            WarehouseLine warehouseLine = await warehouse_line_res.FirstOrDefaultAsync(x => x.WarehouseLineCode == taskOrder.WarehouseCode);
                            box.Id_WarehouseLine = warehouseLine.Id_WarehouseLine;
                            box.WarehouseLine = warehouseLine;
                            //update materialbase
                            foreach (var boxgrid in box.BoxGrids)
                            {
                                foreach (var boxposition in boxgrid.BoxPositions)
                                {
                                    if (boxposition.MaterialBase != null)
                                    {
                                        boxposition.MaterialBase.Islock = false;
                                    }
                                  
                                }
                            }
                            await box_res.UpdateAsync(box);
                            await warehouse_line_res.UpdateAsync(warehouseLine);
                            await TaskOrder_res.DeleteAsync(taskOrder);
                            if (string.IsNullOrEmpty(taskOrder.OrderNo))
                            {
                                return new ApiResponseEss(0, "success", "success2");
                            }
                            //mes
                            Custom_InPut custom_InPut = new Custom_InPut();
                            custom_InPut.boxCode = box.BoxCode;
                            custom_InPut.symbol=taskOrder.OrderNo;
                            custom_InPut.result = 1;
                            List<PutInOrder> putInOrders = await putinorder_res.GetListAsync(x => x.Symbol == taskOrder.OrderNo);
                            foreach (var putInOrder in putInOrders)
                            {

                                PutInOrderDto putInOrderDto = new PutInOrderDto
                                {
                                    materialCode = putInOrder.MaterialCode,
                                    quantity = putInOrder.Quantity,
                                    result = 1
                                };
                                custom_InPut.putInOrderDtos.Add(putInOrderDto);
                            }
                            bool res = await  toOutSideInterFace.receiveInWarehouseResult(custom_InPut);
                            if (res)
                            {
                                putInOrders.ForEach(x =>
                                {
                                    x.UpdateTime = DateTime.Now;
                                    x.IsFinish = true;
                                });
                                await putinorder_res.UpdateManyAsync(putInOrders);
                            }

                            return new ApiResponseEss(0, "success", "success2");
                        }
                    }
                    if (InPut.status == "cancel" || InPut.status == "fail")
                    {
                        TaskOrder taskOrder = await TaskOrder_res.FirstOrDefaultAsync(x => x.TaskOrderCode == InPut.taskCode);
                        if (taskOrder == null)
                        {
                            return new ApiResponseEss(0, "success", "fail-未查询到改任务");
                        }
                        if (taskOrder.Type == "入库")
                        {
                            loginHelper.LoginInfoAsync($"task+cancel+入库{InPut.taskCode}");
                            WarehouseLine warehouseLine = await warehouse_line_res.FirstOrDefaultAsync(x => x.WarehouseLineCode == taskOrder.WarehouseCode);
                            warehouseLine.IsOccupy = false;
                            await warehouse_line_res.UpdateAsync(warehouseLine);
                            await TaskOrder_res.DeleteAsync(taskOrder);
                            loginHelper.LoginAsync(InPut, $"TaskStatusChange-任务失败/取消了+{taskOrder.Id_Box + taskOrder.WarehouseCode + taskOrder.TaskOrderCode}");
                            InPut_BaseService15 inPut = new InPut_BaseService15();
                            inPut.User = "ESS";
                            inPut.Note = "ESS失败/取消了任务" + InPut.taskCode + "msg：" + InPut.message + "事件类型：" + InPut.eventType + InPut.containerCode + InPut.isLocationHasContainer + InPut.stationCode + "状态：" + InPut.status;
                            inPut.Type = "异常";
                            await baseService.CreateLog(inPut);
                            return new ApiResponseEss(0, "success", "success2");
                        }
                    }
                }
                if (InPut.eventType== "tote_load")//取箱完成
                {
                    //if(InPut.status == "success")
                    //{
                    //    TaskOrder taskOrder = await TaskOrder_res.FirstOrDefaultAsync(x => x.TaskOrderCode == InPut.taskCode);
                    //    if (taskOrder == null)
                    //    {
                    //        loginHelper.LoginAsync(InPut, $"TaskStatusChange-未查询到改任务+{taskOrder.Id_Box + taskOrder.WarehouseCode + taskOrder.TaskOrderCode}");
                    //        return new ApiResponse("未查询到该任务", false, null);
                    //    }
                    //    if (taskOrder.Type == "入库")                             
                    //    {
                    //        loginHelper.LoginInfoAsync($"tote_load+success+入库{InPut.taskCode}");
                    //        InlethouseLine inlethouseLine=   await inlethouseline_res.FirstOrDefaultAsync(x => x.InlethouseLineCode == taskOrder.InlethouseCode);
                    //        inlethouseLine.IsOccupy = false;
                    //        await inlethouseline_res.UpdateAsync(inlethouseLine);
                    //        Box box = await box_res.FirstOrDefaultAsync(x => x.Id_Box == taskOrder.Id_Box);
                    //        box.InlethouseLine = null;
                    //        await box_res.UpdateAsync(box);
                    //        //signalr
                    //        await UnitOfWorkManager.Current.SaveChangesAsync();
                    //        Tuple<string, HubConnection> tuple = await SingalrMethod.GetConnectionAsync();
                    //        loginHelper.LoginInfoAsync($"tote_load+success+入库+signalr{InPut.taskCode}");
                    //        await tuple.Item2.StopAsync();
                    //        return new ApiResponse("状态修改成功", true, null);
                    //    }
              
                    //}

                }
                return new ApiResponseEss(0, "success", "fail-未查询到改任务");
            }
            catch (Exception ex)
            {
                InPut_BaseService15 inPut = new InPut_BaseService15();
                inPut.User = "ESS";
                inPut.Note = "任务编号：" + InPut.taskCode + "msg：" + InPut.message + "事件类型：" + InPut.eventType + InPut.containerCode + InPut.isLocationHasContainer + InPut.stationCode + "状态：" + InPut.status;
                inPut.Type = "异常";
                loginHelper.LoginAsync(InPut, $"TaskStatusChange任务回调-异常-{inPut.Note}");
               
                return new ApiResponseEss(0, "success", "fail-内部服务器错误");
            }

        }//任务状态


        public async Task<ApiResponse> ReturnTag(InPut_EssService3 InPut)//灭灯
        {
            TaskOrder taskOrder = await TaskOrder_res.FirstOrDefaultAsync(x => x.InlethouseCode == InPut.tagCode);
            if (taskOrder == null|| InPut.eventCode != "LIGHT_OFF")
            {
                loginHelper.LoginAsync(InPut, $"ReturnTage-未查询到灭灯任务+{InPut.tagCode + InPut.display + InPut.eventCode}");
                return new ApiResponse("未查询到灭灯任务", false, null);
            }
            InlethouseLine inlethouseLine=   await inlethouseline_res.FirstOrDefaultAsync(x=>x.InlethouseLineCode==taskOrder.InlethouseCode);
            if(inlethouseLine == null)
            {
                loginHelper.LoginAsync(InPut, $"ReturnTage-未查询到缓存货架+{InPut.tagCode + InPut.display + InPut.eventCode}");
                return new ApiResponse("未查询到缓存货架", false, null);
            }
            Box box=  await box_res.FirstOrDefaultAsync(x=>x.Id_Box==taskOrder.Id_Box);
            if (box == null)
            {
                loginHelper.LoginAsync(InPut, $"ReturnTage-未查询到该箱盒+{InPut.tagCode + InPut.display + InPut.eventCode}");
                return new ApiResponse("未查询到该箱盒", false, null);
            }
            if (taskOrder.Type == "入库")
            {
                inlethouseLine.Box = box;
                box.InlethouseLine = inlethouseLine;
                box.Id_InlethouseLine = inlethouseLine.Id_InlethouseLine;
                await box_res.UpdateAsync(box);
                await inlethouseline_res.UpdateAsync(inlethouseLine);


                InPut_BaseService15 inPut = new InPut_BaseService15();
                inPut.User = "ESS";
                inPut.Note = "入库-灭灯成功" +"-"+ InPut.tagCode + "-" + box.BoxCode + "-" + InPut.eventCode;
                inPut.Type = "灭灯";
                await baseService.CreateLog(inPut);
                //signalr
                await UnitOfWorkManager.Current.SaveChangesAsync();
                Tuple<string, HubConnection> tuple = await SingalrMethod.GetConnectionAsync();
                loginHelper.LoginAsync(InPut, $"SignalrInfo+{tuple.Item1}");
                await tuple.Item2.StopAsync();
                return new ApiResponse("入库-灭灯成功", true, null);
            }
            else if(taskOrder.Type == "出库"&&taskOrder.State=="已到位")
            {
                inlethouseLine.Box = null;
                inlethouseLine.IsOccupy = false;
                box.InlethouseLine=null;
                await box_res.UpdateAsync(box);
                await inlethouseline_res.UpdateAsync(inlethouseLine);
                await TaskOrder_res.DeleteAsync(taskOrder);
                InPut_BaseService15 inPut = new InPut_BaseService15();
                inPut.User = "ESS";
                inPut.Note = "出库-灭灯成功" + "-" + InPut.tagCode + "-" + box.BoxCode + "-" + InPut.eventCode;
                inPut.Type = "灭灯";
                await baseService.CreateLog(inPut);
                //signalr
                await UnitOfWorkManager.Current.SaveChangesAsync();
                Tuple<string, HubConnection> tuple = await SingalrMethod.GetConnectionAsync();
                loginHelper.LoginAsync(InPut, $"SignalrInfo+{tuple.Item1}");
                await tuple.Item2.StopAsync();
                return new ApiResponse("出库-灭灯成功", true, null);
            }
            else
            {
                return new ApiResponse("未查询到符合条件的灭灯请求", false, null);
            }
        }
    }
}
